package com.itheima.service.mongo.impl;

import cn.hutool.core.util.ObjectUtil;
import com.itheima.domain.mongo.Sound;
import com.itheima.domain.mongo.SoundUser;
import com.itheima.service.mongo.SoundService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class SoundServiceImpl implements SoundService {
    @Autowired
    private MongoTemplate mongoTemplate;


    //保存或更新音声文件信息
    @Override
    public Sound saveOrUpdate(Sound sound) {
        // 创建条件查询
        Query query = Query.query(Criteria.where("id").is(sound.getId()));
        //调用findOne查询,操作类是Sound.class获取查询结果
        Sound sound1 = mongoTemplate.findOne(query,Sound.class);
        // 判断如果查询结果不为空
        if(ObjectUtil.isNotNull(sound1)){
            // 创建update修改字段
            Update update = new Update();
            if(ObjectUtil.isNotNull(sound.getReceiveUserId())){
                update.set("receiveUserId",sound.getReceiveUserId());
            }
            if (ObjectUtil.isNotNull(sound.getReceived())) {
                update.set("received",sound.getReceived());
            }
            // 修改第一条数据
            mongoTemplate.updateFirst(query, update, Sound.class);
        }else {
            // 如果查询结果为空则保存
            sound1 = mongoTemplate.save(sound);
        }
        return sound1;
    }

    //查询音声文件
    @Override
    public List<Sound> find(Long userId) {
        System.out.println(userId);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("received").is(false)
                        .and("userId").ne(userId)),
                Aggregation.sample(1L)

        );
        AggregationResults<Sound> aggregate = mongoTemplate.aggregate(aggregation,Sound.class,Sound.class);
        return aggregate.getMappedResults();
    }

    //查询当前可获取数量
    @Override
    public Integer getCount(Long userId,Long minDate,Long maxDate) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("today").gte(minDate).lte(maxDate));
        long count = mongoTemplate.count(query, SoundUser.class);
        return Math.toIntExact(count);
    }

    //保存接受语音用户信息
    @Override
    public void saveSoundUser(SoundUser soundUser) {
        mongoTemplate.save(soundUser);
    }
}
